package org.example.interceptor;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.example.annotation.Login;
import org.example.dto.base.Result;
import org.example.enums.ResultCodeEnum;
import org.example.util.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import java.lang.reflect.Method;

/**
 * app登录拦截器
 *
 * @author hanxi
 */
public class AppInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger(AppInterceptor.class);

    @Value("${spring.profiles.active}")
    private String activeEnv;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return false;
        }
        //判断是否要登陆
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Login app = method.getAnnotation(Login.class);
        boolean isRequiredLogin = false;
        //优先判断方法注解
        if (app != null) {
            isRequiredLogin = app.login();
        } else {
            //再判断类注解
            app = handlerMethod.getMethod().getDeclaringClass().getAnnotation(Login.class);
            if (app != null) {
                isRequiredLogin = app.login();
            }
        }
        if (!isRequiredLogin) {
            return true;
        }
        //客户ID
        String memberIdStr = request.getHeader("memberId");
        if (StringUtils.isBlank(memberIdStr)) {
            logger.warn("用户ID不正确,ID:{}", memberIdStr);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(JSON.toJSONString(new Result(false, ResultCodeEnum.LOGIN.getId(), "参数不正确")));
            return false;
        }


        //获取入参中的用户token令牌
        String token = request.getHeader("token");
        //token令牌不存在，用户重新登录
        if(StringUtils.isEmpty(token)){
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(JSON.toJSONString(new Result(false, ResultCodeEnum.LOGIN.getId(), "请先登录")));
            return false;
        }



        //判断用户令牌是否过期,过期重新登录
        if(!TokenUtil.verify(token)){
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(JSON.toJSONString(new Result(false, ResultCodeEnum.LOGIN.getId(), "验证信息过期，请重新登录")));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {

    }
}
